package com.lepu.app.fun.chat.fragment;

import android.annotation.SuppressLint;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import com.app.application.MyApplication;
import com.app.config.UserConfig;
import com.app.utils.Const;
import com.app.utils.LoginUtil;
import com.app.utils.ObserverConst;
import com.app.utils.Setting;
import com.app.utils.UmengEvent;
import com.app.utils.Utils;
import com.core.lib.core.AsyncRequest;
import com.core.lib.utils.Observer;
import com.core.lib.utils.ObserverManager;
import com.core.lib.utils.main.AppManager;
import com.core.lib.utils.main.LogUtilBase;
import com.core.lib.utils.main.UIHelper;
import com.core.lib.utils.main.UmengHelper;
import com.core.lib.utils.main.UtilityBase;
import com.core.lib.widget.MyDialog;
import com.lepu.app.fun.chat.activity.ChatMainActivity;
import com.lepu.app.fun.chat.adapter.ChatRoomMessageAdapter;
import com.lepu.app.fun.chat.bean.BeanLectureChatUser;
import com.lepu.app.fun.chat.bean.ChatRoomMessage;
import com.lepu.app.fun.chat.bean.ChatRoomSession;
import com.lepu.app.fun.chat.bean.Media;
import com.lepu.app.fun.chat.bean.MutiRoomEntity;
import com.lepu.app.fun.chat.core.ChatDAO;
import com.lepu.app.fun.chat.core.ChatManager;
import com.lepu.app.fun.chat.core.MessageBuilder;
import com.lepu.app.fun.chat.util.ChatConst;
import com.lepu.app.fun.chat.util.ChatRoomCallBack;
import com.lepu.app.fun.chat.util.ChatSendListener;
import com.lepu.app.fun.chat.util.ChatUtil;
import com.lepu.app.fun.chat.util.Constants;
import com.lepu.app.fun.chat.util.SingManager;
import com.lepu.app.fun.chat.util.VoicePlayClickListenerRoomMessage;
import com.lepu.app.fun.my.bean.BeanMyActivityDetail;
import com.lepu.app.widget.CustomTopBarNew;
import com.lepu.app.widget.CustomTopBarNew.OnTopbarNewLeftLayoutListener;
import com.lepu.app.widget.CustomTopBarNew.OnTopbarNewRightButtonListener;
import com.lepu.pasm.R;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;

/**
 * 医生聊天 允许发送文件，图片，语音等
 *
 * @author wxd
 */

public class ChatFragmentLectureRoom extends ChatFragmentBase implements
        OnTopbarNewLeftLayoutListener, OnTopbarNewRightButtonListener,
        AsyncRequest, ChatSendListener, Observer, SwipeRefreshLayout.OnRefreshListener, ChatRoomCallBack {

    private static final int CHAT_TIME_RECEIVE_CHECK = 1500;

    private static final int MSG_INIT_DATA = 10;
    private static final int MSG_LOAD_MORE_DATA = 11;
    private static final int MSG_RECEIVE_DATA_2 = 13;//检查消息队列是否有数据

    private static final String REQUEST_DATA = "request_data";

    private boolean mInitDataSuccess = false;// 是否加载完数据

    private CustomTopBarNew mTopbar = null;

    private ChatRoomMessageAdapter mDataAdapter = null;
    public static LinkedList<ChatRoomMessage> mDataList = new LinkedList<ChatRoomMessage>();
    private ChatRoomSession mChatSession = new ChatRoomSession();
    private BeanMyActivityDetail mBeanMyActivityDetail = new BeanMyActivityDetail();

    private long mSendTime = 0l;
    private long mReceiveTime = 0l;
    private MyDialog mRemoveLectureDialog = null;

    private LinkedList<ChatRoomMessage> mReceiveList = new LinkedList<ChatRoomMessage>();
    private String mReceiveAtMessageID = "";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @SuppressLint("InflateParams")
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        Bundle data = getArguments();
        if (data != null && data.size() > 0) {
            mBeanMyActivityDetail = (BeanMyActivityDetail) data.getSerializable("BeanMyActivityDetail");
        }

        mNeedSendFile = true;
        mIsGroupChat = true;
        mGroupID = mBeanMyActivityDetail.ChatGroupID;
        boolean flag = true;
        if (mBeanMyActivityDetail != null) {
            flag = (mBeanMyActivityDetail.UserRank.equals("2")) ? true : false;
        }
        mNeedSendSound = flag;

        mView = LayoutInflater.from(getActivity()).inflate(
                R.layout.chat_fragment_lecture, null, false);
        super.onCreateView(inflater, container, savedInstanceState);
        init();
        return mView;
    }

    @Override
    public void onResume() {
        super.onResume();

        UmengHelper.onResume(getActivity(),
                UmengEvent.page_jiangzuo_jiangzuoxiangqing_jinrujiangzuo);
    }

    @Override
    public void onPause() {
        super.onPause();

        UmengHelper.onPause(getActivity(),
                UmengEvent.page_jiangzuo_jiangzuoxiangqing_jinrujiangzuo);
        //ChatManager.getInstance().resetNewMsgCount(mChatSession.getSessionId());
        UtilityBase.closeSoftInput(getActivity());
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        UserConfig.setConfig(MyApplication.getInstance(),
                Const.CONFIG_APP_CHAT_ROOM_AT_RECEIVE_MESSAGE_ID, "");
        mInitDataSuccess = false;
        ObserverManager.getInstance().removeObserver(this);
        stopVoice();
        mHandler.removeCallbacksAndMessages(null);
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);

        if (isVisibleToUser) {
            if (!mInitDataSuccess) {
                // 第一次进入页面获取数据
                mInitDataSuccess = true;
            }
        }
    }

    @Override
    public void onTopbarLeftLayoutSelected() {
        mBaseFragmentActivity.finish(true);
    }

    @Override
    public void onTopbarRightButtonSelected() {
        //讲座医生详情
//		Intent intent = new Intent(mBaseFragmentActivity,
//				MyLectureDoctorInfoActivity.class);
//		intent.putExtra("DoctorID", String.valueOf(mBeanMyActivityDetail.DoctorID));
//		mBaseFragmentActivity.startActivity(intent, true);
    }

    /*
     * 初始化ui控件，不要初始化数据！！！！
     *
     * 初始化控件，需要用mMainView.findViewById 不能使用findViewById，否则程序会闪退的
     */
    private void init() {

        mDataList.clear();
        UmengHelper.CustomEvent(getActivity(), UmengEvent.event_jiangzuo_jiangzuoxiangqing_jinrujiangzuo);

        mTopbar = (CustomTopBarNew) mView.findViewById(R.id.topbar);
        mTopbar.setonTopbarNewLeftLayoutListener(this);
        //mTopbar.setRightText("讲座人资料");
        //mTopbar.setOnTopbarNewRightButtonListener(this);
        mRefreshLayout.setOnRefreshListener(this);

        mChatSendListener = this;

        mTopbar.setTopbarTitle(mBeanMyActivityDetail.ActivityName);

        mTopRightTipLayout.setOnClickListener(mRoomOnClickListener);
        mBottomRightTipLayout.setOnClickListener(mRoomOnClickListener);
        mBottomRightTipTextView.setTag(0);

        if (mBeanMyActivityDetail != null) {
            String flag = mBeanMyActivityDetail.IfCanChat;
            if (flag.equals("1")) {
                mChatInputLayout.setVisibility(View.VISIBLE);
            } else {
                mChatInputLayout.setVisibility(View.GONE);
            }
        }

        // add listen
        ObserverManager.getInstance().addObserver(
                ObserverConst.NOTIFY_CHAT_MESSAGE_LECTURE, this);
        ObserverManager.getInstance().addObserver(
                ObserverConst.NOTIFY_CHAT_MESSAGE_LECTURE_FORBIDEN, this);

        new Thread(new Runnable() {

            @Override
            public void run() {
                initData();
            }
        }).start();

        //请求录音权限
        //Utils.checkAudioPermission();
    }

    private void stopVoice() {
        VoicePlayClickListenerRoomMessage voicePlayClickListenerRoomMessage = VoicePlayClickListenerRoomMessage.currentPlayListener;
        if (voicePlayClickListenerRoomMessage != null) {
            voicePlayClickListenerRoomMessage.stopVoice();
        }
    }

    private void initData() {
        //旧版本分页分页拿数据，新版本加了at功能，做成第一次获取所有300条数据，然后在分页获取数据
        List<ChatRoomMessage> dataList = ChatManager.getInstance().getChatRoomMessages(
                LoginUtil.getUserId(), mBeanMyActivityDetail.ChatGroupID,
                false, 0,300);
        addLastList(dataList);
        mHandler.sendEmptyMessage(MSG_INIT_DATA);
    }

    /**
     * 聊天过程中，监听到被移除讲座，弹框显示
     */
    private void showRemoveLectureChatDialog() {
        if (mRemoveLectureDialog == null || !mRemoveLectureDialog.isShowing()) {
            mRemoveLectureDialog = new MyDialog(getActivity())
                    .setMessage("抱歉，管理员已将您移除讲座群。")
                    .setNegativeButtonSplitImageHide(true)
                    .setPositiveButton(R.string.app_ok,
                            new View.OnClickListener() {

                                @Override
                                public void onClick(View v) {
                                    AppManager.getAppManager().finishActivity(ChatMainActivity.class);
                                }
                            });

            mRemoveLectureDialog.create(null);
            mRemoveLectureDialog.setCancelable(false);
            mRemoveLectureDialog.setCanceledOnTouchOutside(false);
            mRemoveLectureDialog.showMyDialog();
        }
    }

    private void showOperationQuickDialog() {
        MyDialog dialog = new MyDialog(getActivity())
                .setMessage("请不要操作太快！")
                .setNegativeButtonSplitImageHide(true)
                .setPositiveButton(R.string.app_ok,
                        new View.OnClickListener() {

                            @Override
                            public void onClick(View v) {

                            }
                        });

        dialog.create(null);
        dialog.setCancelable(false);
        dialog.setCanceledOnTouchOutside(false);
        dialog.showMyDialog();
    }

    private void addFirstList(List<ChatRoomMessage> dataList) {
        if (dataList != null && dataList.size() > 0) {
            for (int i = 0; i < dataList.size(); i++) {
                ChatRoomMessage message = dataList.get(i);
                message.setContent(ChatUtil.parseGroupChatContent(message.getContent()));
                mDataList.addFirst(message);
                mDataAdapter.addImageData(message, false);
            }
        }
    }

    private void addLastList(List<ChatRoomMessage> dataList) {
        if (dataList != null && dataList.size() > 0) {
            for (int i = dataList.size() - 1; i >= 0; i--) {
                ChatRoomMessage message = dataList.get(i);
                message.setContent(ChatUtil.parseGroupChatContent(message.getContent()));
                mDataList.add(message);
            }
        }
    }

    private void dowithReceiveData() {
        if (mReceiveList != null && mReceiveList.size() > 0) {
            LogUtilBase.LogD(null, "dowithReceiveData size = " + mReceiveList.size());

            SingManager.getInstance().setVoiceReminder();

            Collections.sort(mReceiveList, new SortByStamp(true));
            mDataList.addAll(mReceiveList);

            checkIfScrollBottom(mReceiveList.size());

//            for (int i = mReceiveList.size() - 1; i >= 0; i--) {
//                ChatRoomMessage message = mReceiveList.get(i);
//                mDataAdapter.addImageData(message, true);
//            }

            for (int i = 0; i < mReceiveList.size();i++) {
                ChatRoomMessage message = mReceiveList.get(i);
                mDataAdapter.addImageData(message, true);
            }

            mReceiveList.clear();
            mDataAdapter.notifyDataSetChanged();
            mHandler.sendEmptyMessageDelayed(MSG_RECEIVE_DATA_2,
                    CHAT_TIME_RECEIVE_CHECK);
        }
    }

    private void checkIfScrollBottom(int addSize)
    {
        //scrollBottom();//old
        //new
        //listview 一条数据没有时，会显示气泡。所有加入数组长度判断
        if(Utils.checkListViewIsBottom(mDataListview) || (mDataList != null && mDataList.size()<5)){
            scrollBottom();
        }else{
            mDataListview.setTranscriptMode(ListView.TRANSCRIPT_MODE_NORMAL);
            mBottomRightTipLayout.setVisibility(View.VISIBLE);

            int count = (int) mBottomRightTipTextView.getTag();
            count += addSize;
            mBottomRightTipTextView.setText(String.valueOf(count));
            mBottomRightTipTextView.setTag(count);
        }
    }

    View.OnClickListener mRoomOnClickListener = new View.OnClickListener()
    {

        @Override
        public void onClick(View v) {
            int rid = v.getId();
            switch (rid){
                case R.id.topRightTipLayout:
                    UserConfig.setConfig(MyApplication.getInstance(), Const.CONFIG_APP_CHAT_ROOM_AT_RECEIVE_MESSAGE_ID, "");
                    mTopRightTipLayout.setVisibility(View.GONE);

                    loadAtDataNew();
                    break;
                case R.id.bottomRightTipLayout:

                    clearBottomRightTip();
                    scrollBottom();
                    break;
                default:
                    break;
            }
        }
    };

    private void loadAtDataNew(){
        if(mDataList != null && mDataList.size() > 0){
            int beginIndex = 0;
            for(int i=0;i<mDataList.size();i++){
                if(mReceiveAtMessageID.equals(mDataList.get(i).getMessageId())){
                    beginIndex = i;
                    break;
                }
            }
            mDataListview.setSelection(beginIndex);
            mDataListview.setTranscriptMode(ListView.TRANSCRIPT_MODE_NORMAL);
        }
    }

    private void loadAtDataOld()
    {
        List<ChatRoomMessage> allList = ChatManager.getInstance().getChatRoomMessages(
                LoginUtil.getUserId(), mBeanMyActivityDetail.ChatGroupID, true, 0, 0);
        if(allList != null && allList.size() > 0){
            int beginIndex = 0;
            for(int i=0;i<allList.size();i++){
                if(mReceiveAtMessageID.equals(allList.get(i).getMessageId())){
                    beginIndex = i;
                    break;
                }
            }
            int fromCount = mDataList.size() + mReceiveList.size();
            int needCount = allList.size() - beginIndex;

            List<ChatRoomMessage> dataList = ChatManager.getInstance().getChatRoomMessages(
                    LoginUtil.getUserId(), mBeanMyActivityDetail.ChatGroupID, false, fromCount, needCount);

        }
    }

    private void showAtPerson()
    {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {

                if(mTopRightTipLayout == null)
                {
                    return;
                }

                String messageID = UserConfig.getConfigString(MyApplication.getInstance(),
                        Const.CONFIG_APP_CHAT_ROOM_AT_RECEIVE_MESSAGE_ID, "");
                boolean flag = false;
                if(!TextUtils.isEmpty(messageID))
                {
                    ChatRoomMessage message = ChatDAO.getInstance().getChatRoomMessage(messageID);
                    if(message != null && !TextUtils.isEmpty(message.getContent())){
                        flag = true;
                        mReceiveAtMessageID = messageID;

                        String receiveContent = message.getContent();
                        int visibleFirstPosition = mDataListview.getFirstVisiblePosition();
                        int visibleLastPosition = mDataListview.getLastVisiblePosition();

                        for(int i=visibleFirstPosition;i<visibleLastPosition;i++){
                            String content = mDataList.get(i).getContent();
                            if(receiveContent.equals(content)){
                                flag = false;
                                break;
                            }
                        }
                    }
                }

                if(flag){
                    mTopRightTipLayout.setVisibility(View.VISIBLE);
                }else{
                    UserConfig.setConfig(MyApplication.getInstance(),
                            Const.CONFIG_APP_CHAT_ROOM_AT_RECEIVE_MESSAGE_ID, "");
                }
            }
        },200);
    }

    @SuppressLint("HandlerLeak")
    Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_INIT_DATA:

                    mDataAdapter = new ChatRoomMessageAdapter(getActivity(),
                            ChatFragmentLectureRoom.this, mDataList,
                            ChatConst.TYPE_ONLINE_CHAT_LECTURE,
                            mBeanMyActivityDetail.ChatGroupID,
                            mDataListview, ChatFragmentLectureRoom.this);
                    mDataListview.setAdapter(mDataAdapter);

                    scrollBottom();

                    //检查是否有at我的信息
                   showAtPerson();
                    break;
                case MSG_LOAD_MORE_DATA:

                    mRefreshLayout.setRefreshing(false);

                    List<ChatRoomMessage> dataList = (List<ChatRoomMessage>) msg.obj;
                    if (dataList != null && dataList.size() > 0) {
                        addFirstList(dataList);
                        mDataAdapter.notifyDataSetChanged();
                        mDataListview.setSelection(dataList.size() - 1);
                        mDataListview.setTranscriptMode(ListView.TRANSCRIPT_MODE_NORMAL);
                    }
                    break;
                case MSG_RECEIVE_DATA_2:
                    dowithReceiveData();
                    break;
                default:
                    break;
            }
        }

        ;
    };

    @Override
    public void RequestComplete(Object object, Object data) {
        if (object.equals(REQUEST_DATA)) {
            mBaseFragmentActivity.hideProgressDialog();
        }
    }

    @Override
    public void RequestError(Object object, int errorId, String data) {
        if (object.equals(REQUEST_DATA)) {
            mBaseFragmentActivity.hideProgressDialog();
        }
    }

    // ======================================================

    /**
     * 检查聊天发送数据操作是否太快
     *
     * @return
     */
    private boolean checkChatSendQucik() {
        boolean flag = false;
        if (mSendTime == 0) {
            flag = true;
        } else {
            long value = System.currentTimeMillis() - mSendTime;
            if (value < 1000) {
                LogUtilBase.LogD(null, "操作太快");
                flag = false;
            } else {
                flag = true;
            }
        }
        mSendTime = System.currentTimeMillis();
        return flag;
    }

    /**
     * 接收消息 检查
     *
     * @return
     */
    private boolean checkChatReceiveQucik() {
        boolean flag = false;
        if (mReceiveTime == 0) {
            flag = true;
        } else {
            long value = System.currentTimeMillis() - mReceiveTime;
            if (value < CHAT_TIME_RECEIVE_CHECK) {
                flag = false;
            } else {
                flag = true;
            }
        }
        mReceiveTime = System.currentTimeMillis();
        return flag;
    }

    @Override
    public void sendText(String sendContent) {

        if (!checkChatSendQucik()) {
            showOperationQuickDialog();
            return;
        }

        if (!TextUtils.isEmpty(sendContent)) {

            sendContent = mChatContentEditText.convertMetionString();

            MutiRoomEntity mutiRoomEntity = new MutiRoomEntity();
            mutiRoomEntity.RoomUrl = mBeanMyActivityDetail.ChatGroupID;
            //// TODO: 2016/7/8
            ChatRoomMessage chatRoomMessage = MessageBuilder.buildChatNewTextMessage(mutiRoomEntity, sendContent);

            chatRoomMessage.setChatRoomID(mutiRoomEntity.RoomUrl);

            ChatManager.getInstance().sendChatRoomMessage(mChatSession, chatRoomMessage);

            mChatContentEditText.setText("");
            mDataListview.setSelection(mDataList.size() - 1);
        } else {
            // base fragment sendText
            // 实际上已经做了非空的处理，统一做了提示
        }
    }

    @Override
    public boolean sendPhoto(String imageFilePath) {

        boolean flag = false;
        File file = null;
        if (TextUtils.isEmpty(imageFilePath)) {
            flag = true;
        } else {
            file = new File(imageFilePath);
            if (!file.exists()) {
                flag = true;
            }
        }

        if (flag) {
            UIHelper.showToast(getActivity(), "获取媒体资源失败");
        } else {
            ChatRoomMessage chatMessage = MessageBuilder.buildNewImageRoomMessage(
                    mChatSession, imageFilePath,
                    Constants.Chat.CHAT_IMAGE_STYLE_LARGE, (int) file.length(),
                    false);
            chatMessage.setChatRoomID(mBeanMyActivityDetail.ChatGroupID);
            ChatManager.getInstance().prepareSendMediaMessage(mChatSession,
                    chatMessage);
        }
        return flag;
    }

    @Override
    public void sendPhotos(ArrayList<String> photoFileList) {
        if (photoFileList != null && photoFileList.size() > 0) {
            for (int i = 0; i < photoFileList.size(); i++) {
                String filePath = photoFileList.get(i);
                sendPhoto(filePath);
            }
        }
    }

    @Override
    public boolean sendVoice(String voiceFilePath) {

        File file = new File(voiceFilePath);
        int duration = 0;
        long size = file.length();

        MediaPlayer mp = MediaPlayer.create(getActivity(),
                Uri.parse(voiceFilePath));
        duration = mp.getDuration();// ms

        ChatRoomMessage chatMessage = MessageBuilder.buildNewAudioRoomMessage(
                mChatSession, voiceFilePath, duration, size,
                Constants.Chat.CHAT_MIME_TYPE_AMR, false);
        chatMessage.setChatRoomID(mBeanMyActivityDetail.ChatGroupID);
        ChatManager.getInstance().prepareSendMediaMessage(mChatSession,
                chatMessage);

        return true;
    }

    // ===========================
    @Override
    public void reSendContent(int position) {

        if (!checkChatSendQucik()) {
            showOperationQuickDialog();
            return;
        }

        ChatRoomMessage message = mDataList.get(position);
        mDataList.remove(position);
        mDataAdapter.removeImageData(message);

        if (message.getMessageType() == Constants.Chat.CHAT_MESSAGE_TYPE_TEXT) {
            String sendContent = message.getContent();

            MutiRoomEntity mutiRoomEntity = new MutiRoomEntity();
            mutiRoomEntity.RoomUrl = mBeanMyActivityDetail.ChatGroupID;

            ChatRoomMessage chatRoomMessage = MessageBuilder.buildResendNewTextMessage(mutiRoomEntity, sendContent, message.getMessageId());
            chatRoomMessage.setChatRoomID(mutiRoomEntity.RoomUrl);
            ChatManager.getInstance().sendChatRoomMessage(mChatSession, chatRoomMessage);

            mChatContentEditText.setText("");
            mDataListview.setSelection(mDataList.size() - 1);
        } else if (message.getMessageType() == Constants.Chat.CHAT_MESSAGE_TYPE_IMAGE) {
            Media media = message.getMedia();
            if (media == null) {
                return;
            }

            String imageFilePath = message.getMedia().getFullName();

            File file = new File(imageFilePath);
            if (file.exists()) {
                ChatRoomMessage chatMessage = MessageBuilder
                        .buildResendImageRoomMessage(message.getMessageId(),
                                mChatSession, imageFilePath,
                                Constants.Chat.CHAT_IMAGE_STYLE_LARGE,
                                (int) file.length(), true);
                chatMessage.setChatRoomID(mBeanMyActivityDetail.ChatGroupID);
                ChatManager.getInstance().prepareSendMediaMessage(mChatSession,
                        chatMessage);
            }
        } else if (message.getMessageType() == Constants.Chat.CHAT_MESSAGE_TYPE_AUDIO) {
            Media media = message.getMedia();
            if (media == null) {
                return;
            }
            ChatRoomMessage chatMessage = MessageBuilder.buildResendAudioRoomMessage(
                    message.getMessageId(), mChatSession, media.getFullName(),
                    media.getDuration(), media.getObjectSize(),
                    Constants.Chat.CHAT_MIME_TYPE_AMR);
            chatMessage.setChatRoomID(mBeanMyActivityDetail.ChatGroupID);
            ChatManager.getInstance().prepareSendMediaMessage(mChatSession,
                    chatMessage);
        }
    }

    /**
     * main thread
     */
    @Override
    public void notify(String name, Object sender, Object data) {

        if (name.equals(ObserverConst.NOTIFY_CHAT_MESSAGE_LECTURE_FORBIDEN)) {
            showRemoveLectureChatDialog();
        } else if (name.equals(ObserverConst.NOTIFY_CHAT_MESSAGE_LECTURE)) {

            if (null == mDataAdapter) {
                return;
            }

            int msgWhat = (Integer) sender;

            ChatRoomMessage message = (ChatRoomMessage) data;

            if (null == message) {
                return;
            }

            //new add
            String srcGroupID = mBeanMyActivityDetail.ChatGroupID;
            if (!srcGroupID.equals(message.getChatRoomID())) {
                return;
            }

//			long sessionId = mChatSession.getSessionId();
//			if (sessionId != message.getSessionId()) {
//				return;
//			}

            switch (msgWhat) {
                case Constants.Chat.CHAT_MESSAGE_SENT:
                    LogUtilBase.LogD(null, "Chatting Room:CHAT_MESSAGE_SENT");

                    message.setContent(ChatUtil.parseGroupChatContent(message.getContent()));
                    mDataList.add(message);

                    mDataAdapter.addImageData(message, true);
                    mDataAdapter.notifyDataSetChanged();
                    scrollBottom();
                    break;
                case Constants.Chat.CHAT_MESSAGE_RECEIVED:
                    LogUtilBase.LogD(null, "Chatting Room:CHAT_MESSAGE_RECEIVED");
                    boolean isNew = true;
                    for (int i = mDataList.size() - 1; i >= 0; i--) {
                        if (mDataList.get(i).getMessageId()
                                .equals(message.getMessageId())) {
                            //mDataList.set(i, message);
                            isNew = false;
                            break;
                        }
                    }

                    if (isNew) {
//                        mDataList.add(message);
//                        mDataAdapter.addImageData(message, true);
//                        mDataAdapter.notifyDataSetChanged();
//                        scrollBottom();

                        message.setContent(ChatUtil.parseGroupChatContent(message.getContent()));
                        mReceiveList.add(message);
                        LogUtilBase.LogD(null, "receive data size = " + mReceiveList.size());
                        if (!checkChatReceiveQucik()) {
                            return;
                        }

                        dowithReceiveData();
                    }
                    break;
                case Constants.Chat.CHAT_MESSAGE_CHANGED:
                    LogUtilBase.LogD(null, "Chatting Room:CHAT_MESSAGE_CHANGED");
                    for (int i = mDataList.size() - 1; i >= 0; i--) {
                        if (mDataList.get(i).getMessageId()
                                .equals(message.getMessageId())) {

                            mDataList.set(i, message);
                            break;
                        }
                    }

                    mDataAdapter.notifyDataSetChanged();
                    //scrollBottom();
                    break;
            }
        }
    }

    @Override
    public void onRefresh() {

        new Thread(new Runnable() {

            @Override
            public void run() {

                int fromCount = mDataList.size() + mReceiveList.size();
                List<ChatRoomMessage> dataList = ChatManager.getInstance().getChatRoomMessages(
                        LoginUtil.getUserId(), mBeanMyActivityDetail.ChatGroupID, false, fromCount, Setting.PAGE_SIZE);

                Message msg = mHandler.obtainMessage();
                msg.obj = dataList;
                msg.what = MSG_LOAD_MORE_DATA;
                mHandler.sendMessageDelayed(msg, 100);
            }
        }).start();
    }

    @Override
    public void editTextUpdate(BeanLectureChatUser item) {

        addOtherLayoutHide();

        int UserID = UtilityBase.parseInt(item.UserID);
        mChatContentEditText.mentionUser(UserID, item.NickName,true);

        mChatContentEditText.requestFocus();
        UtilityBase.openSoftInput(getActivity());
    }

    class SortByStamp implements Comparator {

        private boolean isAsc;

        public SortByStamp(boolean asc) {
            isAsc = asc;
        }

        public int compare(Object o1, Object o2) {
            ChatRoomMessage c1 = (ChatRoomMessage) o1;
            ChatRoomMessage c2 = (ChatRoomMessage) o2;

            long t1 = c1.getTimeStamp();
            long t2 = c2.getTimeStamp();
            if (isAsc) {
                if (t2 > t1) {
                    return -1;
                } else if (t1 == t2) {
                    return 0;
                } else {
                    return 1;
                }
            } else {
                if (t2 < t1) {
                    return -1;
                } else if (t1 == t2) {
                    return 0;
                } else {
                    return 1;
                }
            }
        }
    }

}

